<script setup>
import { ref, onMounted, watch } from "vue";
import { useRouter, useRoute } from "vue-router";
import axios from "axios";

const router = useRouter();
const route = useRoute();
const id = ref(route.query.id);

const order = ref({});

// 跳转页面
const jumpTo = (path) => {
  router.push(path);
};
const getOrderDetail = async () => {
  try {
    const res = await axios.get(`${apiUrl}/order/detail/${id.value}`, {
      headers: {
        "Authori-zation": `Bearer ${getToken()}`,
      },
    });

    if (res.data.status === 200) {
      order.value = res.data.data;
    }
  } catch (e) {}
};

const getOrderStatusName = (order) => {
  if (order.status === 0 && order.paid === 0) {
    return "待付款";
  }
  if (order.status === 0 && order.paid === 1) {
    return "待发货";
  }
  if (order.status === 1) {
    return "待收货";
  }
  if (order.status === 2) {
    return "带评价";
  }
  if (order.status === 3) {
    return "已完成";
  }
};

const active = ref(0);

const cancelOrder = async (id) => {
  ElMessageBox.alert("确认取消该订单", "提示", {
    confirmButtonText: "确定",
    callback: async (action) => {
      try {
        const res = await axios.post(
          `${apiUrl}/order/cancel`,
          { id },
          {
            headers: {
              Authorization: `Bearer ${getToken()}`,
            },
          }
        );

        jumpTo("/person?tab=order");
      } catch (e) {}
    },
  });
};

const confirmOrder = async () => {
  try {
    // 使用 Element Plus 的 ElMessageBox 弹出确认框
    await ElMessageBox.confirm("您确定要确认收货吗？", "确认收货", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    });

    // 如果用户点击了确定按钮，执行确认收货的逻辑
    const res = await axios.post(
      `${apiUrl}/order/take`,
      {
        uni: order.value.order_id,
      },
      {
        headers: {
          Authorization: `Bearer ${getToken()}`,
        },
      }
    );

    if (res.data.status === 200) {
      // 使用 Element Plus 的 ElNotification 显示提示信息
      ElNotification({
        title: "成功",
        message: "已确认收货",
        type: "success",
      });

      getOrderDetail();
    }
  } catch (error) {
    // 如果用户点击了取消按钮，或者请求失败，不执行任何操作
    if (error !== "cancel") {
      console.error("确认收货失败:", error);
    }
  }
};

onMounted(() => {
  getOrderDetail();
});

watch(
  () => route.query,
  async (newQuery, oldQuery) => {
    id.value = newQuery.id;
    getOrderDetail();
  },
  { deep: true, immediate: true }
);
</script>

<template>
  <div class="box">
    <div class="mid" v-if="JSON.stringify(order).length > 10">
      <div class="statusBox">
        <div class="item" :class="{ active: order.status >= 0 }">待支付</div>
        <div class="item" :class="{ active: order.status >= 0 && order.paid === 1 }">
          待发货
        </div>
        <div class="item" :class="{ active: order.status >= 1 }">待收货</div>
        <div class="item" :class="{ active: order.status >= 2 }">待评价</div>
        <div class="item" :class="{ active: order.status >= 3 }">已完成</div>
      </div>

      <div class="info">
        <div class="title">收件信息</div>
        <div class="address1">
          <div class="name">{{ order.real_name }}</div>
          <div class="phone">{{ order.user_phone }}</div>
        </div>
        <div class="address2">
          <div class="addressDetail1">{{ order.user_address }}</div>
        </div>
      </div>

      <div class="info">
        <div class="title">订单信息</div>
        <div class="item">
          <div class="date">订单日期：{{ order.add_time_y }}</div>
          <div class="code">订单编号：{{ order.order_id }}</div>
        </div>

        <div class="item" v-for="(item, index) in order.cartInfo" :key="index">
          <div class="cover">
            <img :src="item.productInfo.image" alt="" />
          </div>
          <div class="infoBox">
            <div class="name">{{ item.productInfo.store_name }}</div>
            <div class="priceBox">
              <div class="price">
                ￥{{ item.productInfo.price }}/{{ $t("productList.unit") }}
              </div>
              <div class="num">数量: {{ item.cart_num }}</div>
            </div>
          </div>
        </div>
        <div class="totalPrice">
          共{{ order.refund_total_num }}件商品，总金额￥{{
            order.pay_price
          }}（含运费￥0.00）
        </div>
        <div class="item jusItem">
          <div class="label">订单编号</div>
          <div class="value">{{ order.order_id }}</div>
        </div>
        <div class="item jusItem">
          <div class="label">下单时间</div>
          <div class="value">{{ order._add_time }}</div>
        </div>
        <div class="item jusItem">
          <div class="label">支付状态</div>
          <div class="value">{{ getOrderStatusName(order) }}</div>
        </div>
        <div class="item jusItem" v-if="order.status >= 1">
          <div class="label">物流公司</div>
          <div class="value">{{ order.delivery_name }}</div>
        </div>
        <div class="item jusItem" v-if="order.status >= 1">
          <div class="label">顺丰快递</div>
          <div class="value">{{ order.delivery_id }}</div>
        </div>
      </div>

      <div class="btnBox">
        <el-button
          type="primary"
          style="width: 150px"
          v-if="order.status === 0 && order.paid === 0"
          @click="jumpTo('/payOrder?id=' + order.order_id)"
          >立即支付</el-button
        >
        <el-button
          type="primary"
          style="width: 150px"
          v-if="order.status === 1"
          @click="confirmOrder()"
          >确认收货</el-button
        >
        <el-button
          type="primary"
          style="width: 150px"
          v-if="order.status === 2"
          @click="jumpTo('/orderEvaluation?id=' + order.order_id)"
          >立即评价</el-button
        >
        <div
          class="btn"
          v-if="order.status === 0 && order.paid === 0"
          @click="cancelOrder"
        >
          取消订单
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
.mid {
  width: 800px;
  margin: 0 auto;
  overflow: hidden;
  .statusBox {
    display: flex;
    background-color: #fff;
    padding: 20px 30px;
    justify-content: space-between;
    position: relative;
    margin-top: 20px;
    padding-bottom: 50px;

    .item {
      position: relative;
      color: #999;
      &::before {
        content: "";
        position: absolute;
        width: 10px;
        height: 10px;
        border-radius: 10px;
        border: 1px solid #999;
        top: 30px;
        left: 13px;
      }

      &::after {
        content: "";
        position: absolute;
        width: 100px;
        height: 1px;
        background-color: #999;
        top: 35px;
        left: 55px;
      }

      &.active {
        color: #000;
        &::before {
          background-color: #000;
        }
        &::after {
          background-color: #000;
        }
      }

      &:last-child {
        &::after {
          display: none;
        }
      }
    }
  }
}

.box {
  background-color: #f5f5f5;
  height: 100%;
}

.info {
  background-color: #fff;
  margin-top: 20px;
  padding: 20px 30px;

  .title {
    font-size: 16px;
    margin-bottom: 20px;
    font-weight: bold;
  }

  .address1 {
    display: flex;
    margin-bottom: 20px;
    font-size: 16px;

    .name {
      margin-right: 20px;
      font-size: 14px;
    }

    .phone {
      font-size: 14px;
      position: relative;
      top: 2px;
    }
  }

  .address2 {
    font-size: 14px;
    color: #666;
    display: flex;
    .addressDetail1 {
      margin-right: 10px;
    }
  }

  .item {
    display: flex;
    color: #666;
    overflow: hidden;

    .date {
      margin-right: 20px;
    }

    .cover {
      width: 100px;
      height: 100px;
      img {
        width: 100%;
      }
    }

    .infoBox {
      flex: 2;
      .name {
        color: #000;
        font-weight: bold;
        margin-top: 30px;
        margin-bottom: 10px;
      }
    }

    .totalPrice {
      margin-top: 70px;
      height: 20px;
    }

    .priceBox {
      display: flex;

      .price {
        margin-right: 40px;
        color: #000;
        font-weight: bold;
      }
    }
  }

  .jusItem {
    justify-content: space-between;
    margin-top: 20px;
  }
}

.btnBox {
  margin-top: 30px;
  margin-bottom: 40px;
  display: flex;

  .btn {
    margin-left: 30px;
    line-height: 30px;
    color: #666;
    cursor: pointer;
  }
}
</style>
